import type { DependencyList } from 'react';

import { useRequest } from 'ahooks';
import { Select as AntdSelect, SelectProps as AntdSelectProps } from 'antd';
import { BaseOptionType, DefaultOptionType } from 'antd/es/cascader';
import cs from 'classnames';

import styles from './index.module.scss';

export type SelectProps<
  ValueType = any,
  OptionType extends BaseOptionType | DefaultOptionType = DefaultOptionType
> = AntdSelectProps<ValueType, OptionType> & {
  request?: () => Promise<OptionType[]>;
  refreshDeps?: DependencyList;
};

const Select = <
  ValueType = any,
  OptionType extends BaseOptionType | DefaultOptionType = DefaultOptionType
>({
  request,
  refreshDeps,
  className,
  ...rest
}: SelectProps<ValueType, OptionType>) => {
  const data = useRequest(
    async () => {
      const res = await request!();

      return res;
    },
    {
      manual: request ? false : true,
      refreshDeps
    }
  );

  return (
    <AntdSelect<ValueType, OptionType>
      className={cs(styles['tree-select'], className)}
      options={data.data}
      {...rest}
    />
  );
};

export default Select;
